package com.ccl.iot.views;

import android.content.Context;
import android.widget.BaseAdapter;

import com.ccl.iot.publics.UIUtils;

import java.util.ArrayList;

public abstract class StandardAdapter<TYPE> extends BaseAdapter {
    protected Context iContext = null;
    protected ArrayList<TYPE> iItems = null;

    protected int iItemWidth = 0, iItemHeight = 0;

    public StandardAdapter(Context aContext) {
        iContext = aContext;
    }

    public Context getContext() {
        return iContext;
    }

    public void setItems(ArrayList<TYPE> aItems) {
        iItems = aItems;

        UIUtils.postTaskSafely(new Runnable() {

            @Override
            public void run() {
                notifyDataSetChanged();
            }
        });
    }

    public ArrayList<TYPE> getItems() {
        return iItems;
    }

    public boolean contansItem(TYPE aItem) {
        if (aItem != null && iItems != null) {
            return iItems.contains(aItem);
        }

        return false;
    }

    public boolean addItem(TYPE aItem) {
        if (aItem != null) {
            if (iItems == null) {
                iItems = new ArrayList<TYPE>();
            } else if (iItems.contains(aItem)) {
                return true;
            }

            if (iItems.add(aItem)) {
                UIUtils.postTaskSafely(new Runnable() {

                    @Override
                    public void run() {
                        notifyDataSetChanged();
                    }
                });

                return true;
            }
        }

        return false;
    }

    public boolean removeItem(TYPE aItem) {
        if (aItem != null && iItems != null) {
            if (iItems.remove(aItem)) {
                this.notifyDataSetChanged();

                return true;
            }
        }

        return false;
    }

    @Override
    public int getCount() {
        if (iItems != null) {
            return iItems.size();
        }

        return 0;
    }

    @Override
    public TYPE getItem(int position) {
        if (iItems != null) {
            return iItems.get(position);
        }

        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void removeAllItem() {
        if (iItems != null) {
            iItems.clear();
        }
    }
}
